/* model */
import { IMMessageSendTypeEnum } from "@src/modules/im/imChat/model"
/* types */
import { IMChatMessage } from "@src/modules/im/imChat/types/message"
import { OpenAIMessageItemType, OpenAIMessageRoleEnum } from "@src/component/business/BizChatPanel/chat/model"
import { isFalsy } from "pub-bbx-utils"

function convertIMMessageToAIMessage(imMessage: IMChatMessage): OpenAIMessageItemType {
  
  // 消息内容
  const content = imMessage?.messageContent?.msg || ''
  // 创建时间
  const createTime = imMessage?.createTime
  // 唯一标识
  const id = String(imMessage?.id || '')
  
  // 消息类型
  const sendType = imMessage?.sendType
  
  // 用户消息
  if (sendType == IMMessageSendTypeEnum.CUSTOMER) {
    return {
      role: OpenAIMessageRoleEnum.User,
      content: content,
      createTime,
      id
    }
  }
  
  // 客服消息
  if (sendType == IMMessageSendTypeEnum.CUSTOMER_SERVICE) {
    return {
      role: OpenAIMessageRoleEnum.Assistant,
      content: content,
      createTime,
      id
    }
  }
  
  throw new Error('不支持的消息类型')
}

function convertIMMessageListToAIMessageList(imMessageList: IMChatMessage[]): OpenAIMessageItemType[] {
  // 只支持客户和客服发送的消息
  const supportIMMessageSendTypeList = [
    IMMessageSendTypeEnum.CUSTOMER,
    IMMessageSendTypeEnum.CUSTOMER_SERVICE,
  ]
  // 过滤不支持的消息类型
  const filteredIMMessageList = imMessageList.filter((imMessage) => {
    return supportIMMessageSendTypeList.includes(imMessage.sendType)
  })
  // 过滤历史消息
  const filteredHistoryIMMessageList = filteredIMMessageList.filter((imMessage) => {
    return isFalsy(imMessage.isHistoryConversation)
  })
  // 转换消息
  return filteredHistoryIMMessageList.map(convertIMMessageToAIMessage)
}

export {
  convertIMMessageToAIMessage,
  convertIMMessageListToAIMessageList
}